<?php

/**
 * This is the model class for table "{{photo}}".
 *
 * The followings are the available columns in table '{{photo}}':
 * @property integer $id
 * @property string $name
 * @property string $picture
 * @property integer $status
 * @property integer $display_order
 * @property string $description
 * @property string $language
 * @property integer $album_id
 * @property string $create_date
 * @property string $created_by
 * @property string $update_date
 * @property string $updated_by
 * @property integer $hits
 *
 * The followings are the available model relations:
 * @property Album $album
 */
class Photo extends CActiveRecord {

     const SCENARIO_SEARCH = 'search';
    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';

    
    /**
     *Supporting order photo
     * @var int 
     */
    public $previousPhotoID = null;
    
    /**
     *Supporting order photo
     * @var int 
     */
    public $nextPhotoID = null;
    
    /**
     * Get $maxOrder when beforeSave()
     * @var int 
     */
    protected $maxOrder = null;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Photo the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{photo}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
	    array('name', 'required', 'message' => t('MSG_REQUIRED', 'messages')),
	    array('status, display_order, hits, album_id', 'numerical', 'integerOnly' => true, 'message' => t('MSG_WRONG_NUMBER', 'messages')),
	    array('name, picture', 'length', 'max' => 100, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages')),
	    array('description', 'length', 'max' => 1000, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages')),
	    array('language', 'length', 'max' => 25, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages')),
	    array('album_id', 'required', 'on' => array('create', 'update'), 'message' => t('MSG_REQUIRED', 'messages')),
	    //array('picture', 'length', 'max' => 100, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages'), 'on' => 'create'),
	    array('picture', 'file', 'types' => 'jpg,jpeg,bmp,png,gif', 'maxSize' => 1024 * 1024, // 1MB
		'tooLarge' => t('MSG_IMAGE_TOO_LARGE', 'messages'),
		'wrongType' => t('MSG_FILE_WRONG_TYPE', 'messages'),
		'allowEmpty' => false, 'on' => Photo::SCENARIO_CREATE),
	    array('picture', 'length', 'max' => 100, 'tooLong' => t('MSG_STRING_TOO_LONG', 'messages'), 'on' => 'create'),
	    array('picture', 'file', 'types' => 'jpg,jpeg,bmp,png,gif', 'maxSize' => 1024 * 1024, // 1MB
		'tooLarge' => t('MSG_IMAGE_TOO_LARGE', 'messages'),
		'wrongType' => t('MSG_FILE_WRONG_TYPE', 'messages'),
		'allowEmpty' => true, 'on' => Photo::SCENARIO_UPDATE),
	    array('create_date, update_date', 'safe'),
	    // The following rule is used by search().
	    // Please remove those attributes that should not be searched.
	    array('id, name, picture, status, display_order, description, language, create_date, created_by, update_date, updated_by, hits', 'safe', 'on' => 'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'album' => array(self::BELONGS_TO, 'Album', 'album_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => t('LBL_ID', 'gallery'),
	    'name' => t('LBL_PHOTO_NAME', 'gallery'),
	    'picture' => t('LBL_PICTURE', 'gallery'),
	    'status' => t('LBL_STATUS', 'gallery'),
	    'display_order' => t('LBL_DISPLAY_ORDER', 'gallery'),
	    'description' => t('LBL_DESCRIPTION', 'gallery'),
	    'language' => t('LBL_LANGUAGE', 'gallery'),
	    'album_id' => t('LBL_ALBUM', 'gallery'),
	    'create_date' => t('LBL_CREATEDATE', 'gallery'),
	    'created_by' => t('LBL_CREATEDBY', 'gallery'),
	    'update_date' => t('LBL_UPDATE_DATE', 'gallery'),
	    'updated_by' => t('LBL_UPDATED_BY', 'gallery'),
	    'hits' => t('LBL_HITS', 'gallery'),
	);
    }

    public function search($pageSize = 10) {
	// It has a special thing.
	//My algorithm is load $pageSize + 1 items
	//Set previous album id and next album id
	//And remove the last item

	if (isset($_GET['page'])) {
	    $page = & $_GET['page'];
	} else {
	    $page = 1;
	}

	$criteria = new CDbCriteria;

	$criteria->compare('id', $this->id);
	$criteria->compare('album_id', $this->album_id);
	
	if (isset($this->name)) {
	    $this->name = trim($this->name);
	}
	$criteria->addSearchCondition('name', $this->name);
	$criteria->compare('picture', $this->picture, true);
	$criteria->compare('status', $this->status);
	$criteria->compare('display_order', $this->display_order);
	$criteria->compare('description', $this->description, true);

	if ($this->language == "*") {
	    $this->language = "";
	}
	$criteria->compare('language', $this->language, true);

	$criteria->compare('create_date', $this->create_date, true);
	$criteria->compare('created_by', $this->created_by, true);
	$criteria->compare('update_date', $this->update_date, true);
	$criteria->compare('updated_by', $this->updated_by, true);
	$criteria->compare('hits', $this->hits);

	$itemCount = self::model()->count($criteria);
	
	if ($pageSize != null) {
	    
	    if ($page != 1) {
		//If result page < $page, set $page to 1
		$totalPage = $itemCount / $pageSize > intval($itemCount / $pageSize) ? intval($itemCount / $pageSize) + 1 : intval($itemCount / $pageSize);
		if ($totalPage < $page) {
		    $page = $totalPage;
		}
	    }
	    
	    $criteria->offset = ($page - 1) * $pageSize;
	    $criteria->limit = $pageSize + 1;
	} else {
	    $pageSize = $itemCount;
	}
	
	$criteria->order = 'display_order ASC';
	$photos = self::model()->findAll($criteria);
	$len = count($photos);

	//Set previous and next album ID
	if ($len > 1) {
	    $photos[0]->nextPhotoID = $photos[1]->id;
	    $photos[$len - 1]->previousPhotoID = $photos[$len - 2]->id;

	    for ($i = 1; $i < $len - 1; $i++) {
		$photos[$i]->nextPhotoID = $photos[$i + 1]->id;
		$photos[$i]->previousPhotoID = $photos[$i - 1]->id;
	    }
	}

	//Remove the last item
	if ($len > $pageSize) {
	    $photos = array_slice($photos, 0, $pageSize);
	}

	//Set to data provider to show on gridview
	$photoProvider = new CActiveDataProvider($this, array('data' => array()));
	$photoProvider->data = $photos;

	//Set pagination
	$pagination = new CPagination();
	$pagination->pageSize = $pageSize;
	$pagination->itemCount = $itemCount;
	$photoProvider->pagination = $pagination;

	//Set total item number for gridview
	$photoProvider->totalItemCount = $pagination->itemCount;
	return $photoProvider;
    }

    public function getPhotoByAlbum($album_id) {
	return $this->findAll('album_id=:album_id', array(':album_id' => $album_id));
    }

    public function beforeSave() {
	if (parent::beforeSave()) {
	    $current_date = date(LGConstant::DATE_FORMAT_FOR_DATABASE);
	    $logedInUser = User::model()->findByPk(Yii::app()->user->id);

	    if ($this->isNewRecord) {
		$this->create_date = $current_date;
		$this->created_by = $logedInUser->username;
	    }

	    $this->update_date = $current_date;
	    $this->updated_by = $logedInUser->username;

	    if ($this->scenario === Album::SCENARIO_CREATE) {
		$criteria = new CDbCriteria;
		$criteria->select = 'MAX(display_order) as maxOrder';
		$album = self::model()->find($criteria);
		$this->display_order = $album->maxOrder + 1;
	    }

	    return true;
	}
	else
	    return false;
    }

    protected function afterFind() {
	// convert to display format
	$this->update_date = strtotime($this->update_date);
	$this->update_date = date(LGConstant::DATE_FORMAT, $this->update_date);
	if ($this->update_date == LGConstant::DATE_DEFAULT)
	    $this->update_date = '';
	
	parent::afterFind();
    }

    protected function afterDelete() {
	$path = MEDIA_FOLDER . DS . 'gallery' . DS . $this->picture;
	if (file_exists($path))
	    unlink(MEDIA_FOLDER . DS . 'gallery' . DS . $this->picture);
	parent::afterDelete();
    }

    public function getPhotoByAlbumId($id, $lang) {
	$criteria = new CDbCriteria();
	$criteria->addCondition("language = '" . $lang . "'");
	$criteria->addCondition("language = '*'", 'OR');
	$criteria->addCondition('album_id =' . $id);
	$criteria->addCondition('status =' . LGConstant::PUBLISH_STATUS);
	$criteria->order = 'display_order ASC';
	return new CActiveDataProvider($this, array('criteria' => $criteria,
	    'pagination' => false));
    }

    public function getPhotoByAlbumIdAndMonth($albumId, $month, $year, $lang) {
	$criteria = new CDbCriteria();
	$criteria->addCondition("language = '" . $lang . "'");
	$criteria->addCondition("language = '*'", 'OR');
	$criteria->addCondition('album_id =' . $albumId);
	$criteria->addCondition('status =' . LGConstant::PUBLISH_STATUS);

	$startDate = date(LGConstant::DATE_FORMAT_FOR_DATABASE, mktime(0, 0, 0, $month, 1, $year));
	$endDate = date(LGConstant::DATE_FORMAT_FOR_DATABASE, mktime(0, 0, 0, $month + 1, 0, $year));
	$criteria->addCondition("create_date > '$startDate' AND create_date < '$endDate'");
	return new CActiveDataProvider($this, array('criteria' => $criteria,
	    'pagination' => array('pageSize' => LGConstant::FRONTEND_GALLERY_PHOTO_PAGE_SIZE),));
    }

}